package com.movecar.ui;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.movecar.R;
import com.movecar.listview.WaterFallListView;
import com.movecar.listview.WaterFallListView.IXListViewListener;
import com.movecar.model.CloudBeansBean;
import com.movecar.model.ClubBean;
import com.movecar.model.GroupBean;
import com.movecar.utils.Alert;
import com.movecar.utils.AppConfig;
import com.movecar.utils.DataStore;
import com.movecar.utils.HttpPostRequestAsyncTask;
import com.movecar.utils.RequestResultCallback;
import com.movecar.utils.imageloader.Constants;
import com.movecar.utils.imageloader.Utils;
import com.movecar.widget.CustomProgressDialog;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 俱乐部列表
 * 
 * @author Zhao.JQ
 * 
 */
public class ClubActivity extends Activity implements OnClickListener, IXListViewListener {

	// private ListView mListView;
	private CustomProgressDialog progressDialog = null;
	protected WaterFallListView mXList;
	private List<ClubBean> mDataList = new ArrayList<ClubBean>();
	private List<ClubBean> resultList = new ArrayList<ClubBean>();
	private DataAdapter dataAdapter;
	private boolean flgMore = false;
	private String pageNo = "0";
	private ImageLoader imageLoader = null;
	private RelativeLayout right_btn;
	private RelativeLayout right_btn_click;
	private Button btn_left;
	private CloudBeansBean mCloudBeansBean = null;
	private String strFlag = "0";
	private String keyword = "";

	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.club);
		initView();
	}

	private void initView() {
		imageLoader = ImageLoader.getInstance();
		// imageLoader.init(Constants.imageLoaderConfiguration(this));
		dataAdapter = new DataAdapter(ClubActivity.this);
		// 俱乐部
		mXList = (WaterFallListView) findViewById(R.id.mListView);
		mXList.setPullRefreshEnable(true);
		mXList.setPullLoadEnable(true);
		mXList.setXListViewListener(this);
		mXList.setAdapter(dataAdapter);
		right_btn = (RelativeLayout) findViewById(R.id.right_btn);
		right_btn.setVisibility(View.VISIBLE);
		right_btn.setOnClickListener(this);
		btn_left = (Button) findViewById(R.id.btn_left);
		btn_left.setVisibility(View.VISIBLE);
		btn_left.setOnClickListener(this);

		right_btn_click = (RelativeLayout) findViewById(R.id.right_btn_click);
		right_btn_click.setOnClickListener(this);
		startProgressDialog();
		getSeller("");
		// 获得SharedPreferences对象
		SharedPreferences MyLocation = getSharedPreferences("location", Context.MODE_PRIVATE);
		String location = MyLocation.getString("location", "");

	}

	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.right_btn:
			right_btn_click.setVisibility(View.VISIBLE);
			right_btn.setVisibility(View.GONE);
			strFlag = "1";
			flgMore = false;
			getSeller("");
			break;
		case R.id.right_btn_click:
			right_btn.setVisibility(View.VISIBLE);
			right_btn_click.setVisibility(View.GONE);
			strFlag = "0";
			flgMore = false;
			getSeller("");
			break;
		case R.id.btn_left:
			Intent intent = new Intent();
			intent.setClass(ClubActivity.this, ClubClassificationActivity.class);
			startActivityForResult(intent, 0);

			break;
		default:
			break;
		}

	}

	protected void onResume() {

		super.onResume();

	}

	@SuppressWarnings("unchecked")
	private void getSeller(String keyword) {

		List<NameValuePair> params = new ArrayList<NameValuePair>(); // 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "queryCloudSellerNew1")); // 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		params.add(new BasicNameValuePair("pageNo", pageNo));
		params.add(new BasicNameValuePair("strFlag", strFlag));
		params.add(new BasicNameValuePair("keyword", keyword));
		params.add(new BasicNameValuePair("pmId", "0"));

		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {

				stopProgressDialog();

				Type type = new TypeToken<List<ClubBean>>() {
				}.getType();
				Gson gson = new Gson();
				String result = (String) object;
				Object fromJson = gson.fromJson(result, type);

				try {
					mDataList = (List<ClubBean>) fromJson;
				} catch (Exception e) {
					return;
				}

				if (mDataList != null) {
					if (flgMore) {
						if (mDataList.size() == 0) {

							Toast.makeText(getApplicationContext(), "已经加载全部", Toast.LENGTH_SHORT).show();

							if (!"1".equals(pageNo)) {
								pageNo = String.valueOf(Integer.parseInt(pageNo) - 1);
							} else {
								pageNo = "0";
							}
							resetXList();
						} else {
							resultList.clear();
							for (ClubBean bean : mDataList) {

								resultList.add(bean);
							}
							dataAdapter.addItemLast(resultList);
							resetXList();

						}
					} else {
						if (mDataList.size() == 0) {
							Toast.makeText(getApplicationContext(), "已经加载全部", Toast.LENGTH_SHORT).show();
							resultList.clear();
							resetXList();
						}
						resultList.clear();
						for (ClubBean bean : mDataList) {
							resultList.add(bean);
						}
						dataAdapter.addItemTop(resultList);
						dataAdapter.notifyDataSetChanged();
						resetXList();
					}

				} else {
					Toast.makeText(getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			public void onFail(String exception) {

				stopProgressDialog();
				Alert.error(ClubActivity.this,"与服务器连接失败，请检查网络");
				resetXList();

			}
		}, ClubBean.class, AppConfig.CLUB).execute(params);
	}

	protected void resetXList() {

		mXList.setRefreshTime(new SimpleDateFormat("H:mm", Locale.CHINA).format(new Date()));
		mXList.stopRefresh();
		mXList.stopLoadMore();
	}

	class DataAdapter extends BaseAdapter {

		private Activity activity;
		private LayoutInflater inflater;
		private LinkedList<ClubBean> resultList;

		DataAdapter(Activity activity) {

			this.activity = activity;
			inflater = LayoutInflater.from(activity);
			resultList = new LinkedList<ClubBean>();
		}

		public void addItemLast(List<ClubBean> datas) {
			resultList.addAll(datas);
		}

		public void addItemTop(List<ClubBean> datas) {
			resultList.clear();
			for (ClubBean info : datas) {
				resultList.add(info);
			}
		}

		@Override
		public int getCount() {

			return resultList.size();
		}

		@Override
		public Object getItem(int arg0) {

			return resultList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {

			return arg0;
		}

		@Override
		public View getView(final int position, View view, ViewGroup arg2) {
			View itemView = null;

			if (view == null) {
				// viewHolder = new ViewHolder();
				view = inflater.inflate(R.layout.club_item, null);
				itemView = view;
				view.setTag(itemView);

				// view.setTag(viewHolder);
			} else {
				itemView = (View) view.getTag();
				// viewHolder = (ViewHolder) view.getTag();
			}
			ImageView club_img = (ImageView) itemView.findViewById(R.id.club_img);
			ImageView watermark1 = (ImageView) itemView.findViewById(R.id.watermark1);
			ImageView watermark2 = (ImageView) itemView.findViewById(R.id.watermark2);
			ImageView watermark3 = (ImageView) itemView.findViewById(R.id.watermark3);
			ImageView watermark4 = (ImageView) itemView.findViewById(R.id.watermark4);
			ImageView type = (ImageView) itemView.findViewById(R.id.type);
			TextView club_title = (TextView) itemView.findViewById(R.id.club_title);
			TextView publicCount = (TextView) itemView.findViewById(R.id.publicCount);
			TextView friendCount = (TextView) itemView.findViewById(R.id.friendCount);
			final Button attention = (Button) itemView.findViewById(R.id.attention);
			TextView friendCount_title = (TextView) itemView.findViewById(R.id.friendCount_title);
			TextView club_recomand_name = (TextView) itemView.findViewById(R.id.club_recomand_name);
			LinearLayout watermark_bg = (LinearLayout) itemView.findViewById(R.id.watermark_bg);

			club_title.setText(resultList.get(position).getSectionName());

			publicCount.setText(resultList.get(position).getPublicCount());

			friendCount.setText(resultList.get(position).getFriendCount());
			if (!resultList.get(position).getRecommendUserNickname().equals("")) {
				club_recomand_name.setText("(推荐人: " + resultList.get(position).getRecommendUserNickname() + ")");
			}else{
				club_recomand_name.setText("");
			}

			friendCount.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent();
					intent.setClass(activity, NewHomeActivity.class);
					intent.putExtra("sectionId", resultList.get(position).getSectionId());
					intent.putExtra("sectionName", resultList.get(position).getSectionName());

					startActivity(intent);
				}
			});
			friendCount_title.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent();
					intent.setClass(activity, NewHomeActivity.class);
					intent.putExtra("sectionId", resultList.get(position).getSectionId());
					intent.putExtra("sectionName", resultList.get(position).getSectionName());

					startActivity(intent);
				}
			});
			if ("0".equals(resultList.get(position).getScreenFlag())) {
				attention.setBackgroundResource(R.drawable.club_unfollow);

			} else {
				attention.setBackgroundResource(R.drawable.club_follow);

			}
			if ("0".equals(resultList.get(position).getType())) {
				type.setImageResource(R.drawable.club_authority);
			} else if ("2".equals(resultList.get(position).getType())) {
				type.setImageResource(R.drawable.club_recommend);
			}
			attention.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					startProgressDialog();
					followJsonData(resultList.get(position).getSectionId());
					if ("0".equals(resultList.get(position).getScreenFlag())) {
						resultList.get(position).setScreenFlag("1");
						attention.setBackgroundResource(R.drawable.club_follow);
					} else {
						resultList.get(position).setScreenFlag("0");
						attention.setBackgroundResource(R.drawable.club_unfollow);
					}

				}
			});
			if (!"".equals(resultList.get(position).getLogo())) {
				club_img.setVisibility(View.VISIBLE);
				imageLoader.displayImage(AppConfig.HOST + resultList.get(position).getLogo(), club_img,
						Constants.image_display_options, AppConfig.animateListener);
			} else {
				club_img.setImageResource(R.drawable.club_img4);
			}
			List<String> list = Utils.stringToList(resultList.get(position).getWmString(), ", ");
			if (list.size() <= 4 && list.size() > 0) {
				watermark_bg.setVisibility(View.VISIBLE);
				switch (list.size()) {
				case 0:
					watermark1.setVisibility(View.GONE);
					watermark2.setVisibility(View.GONE);
					watermark3.setVisibility(View.GONE);
					watermark4.setVisibility(View.GONE);
					break;
				case 1:
					watermark1.setVisibility(View.VISIBLE);
					watermark2.setVisibility(View.GONE);
					watermark3.setVisibility(View.GONE);
					watermark4.setVisibility(View.GONE);
					imageLoader.displayImage(AppConfig.HOST + list.get(0), watermark1, Constants.image_display_options,
							AppConfig.animateListener);
					break;
				case 2:
					watermark1.setVisibility(View.VISIBLE);
					watermark2.setVisibility(View.VISIBLE);
					watermark3.setVisibility(View.GONE);
					watermark4.setVisibility(View.GONE);
					imageLoader.displayImage(AppConfig.HOST + list.get(0), watermark1, Constants.image_display_options,
							AppConfig.animateListener);
					imageLoader.displayImage(AppConfig.HOST + list.get(1), watermark2, Constants.image_display_options,
							AppConfig.animateListener);
					break;
				case 3:
					watermark1.setVisibility(View.VISIBLE);
					watermark2.setVisibility(View.VISIBLE);
					watermark3.setVisibility(View.VISIBLE);
					watermark4.setVisibility(View.GONE);
					imageLoader.displayImage(AppConfig.HOST + list.get(0), watermark1, Constants.image_display_options,
							AppConfig.animateListener);
					imageLoader.displayImage(AppConfig.HOST + list.get(1), watermark2, Constants.image_display_options,
							AppConfig.animateListener);
					imageLoader.displayImage(AppConfig.HOST + list.get(2), watermark3, Constants.image_display_options,
							AppConfig.animateListener);
					break;
				case 4:
					watermark1.setVisibility(View.VISIBLE);
					watermark2.setVisibility(View.VISIBLE);
					watermark3.setVisibility(View.VISIBLE);
					watermark4.setVisibility(View.VISIBLE);
					imageLoader.displayImage(AppConfig.HOST + list.get(0), watermark1, Constants.image_display_options,
							AppConfig.animateListener);
					imageLoader.displayImage(AppConfig.HOST + list.get(1), watermark2, Constants.image_display_options,
							AppConfig.animateListener);
					imageLoader.displayImage(AppConfig.HOST + list.get(2), watermark3, Constants.image_display_options,
							AppConfig.animateListener);
					imageLoader.displayImage(AppConfig.HOST + list.get(3), watermark4, Constants.image_display_options,
							AppConfig.animateListener);
					break;

				default:
					break;
				}
			} else if (list.size() > 4) {
				watermark_bg.setVisibility(View.VISIBLE);
				watermark1.setVisibility(View.VISIBLE);
				watermark2.setVisibility(View.VISIBLE);
				watermark3.setVisibility(View.VISIBLE);
				watermark4.setVisibility(View.VISIBLE);
				imageLoader.displayImage(AppConfig.HOST + list.get(0), watermark1, Constants.image_display_options,
						AppConfig.animateListener);
				imageLoader.displayImage(AppConfig.HOST + list.get(1), watermark2, Constants.image_display_options,
						AppConfig.animateListener);
				imageLoader.displayImage(AppConfig.HOST + list.get(2), watermark3, Constants.image_display_options,
						AppConfig.animateListener);
				imageLoader.displayImage(AppConfig.HOST + list.get(3), watermark4, Constants.image_display_options,
						AppConfig.animateListener);

			} else {
				watermark_bg.setVisibility(View.GONE);
			}

			view.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					if ("0".equals(resultList.get(position).getType())) {
						Intent intent = new Intent();
						intent.setClass(activity, ClubDetailActivity.class);
						intent.putExtra("sectionId", resultList.get(position).getSectionId());
						intent.putExtra("position", position);
						activity.startActivityForResult(intent, AppConfig.REQUEST_CLUB);
					} else if ("2".equals(resultList.get(position).getType())) {
						Intent intent = new Intent();
						intent.setClass(activity, RecommendClubDetailActivity.class);
						intent.putExtra("sectionId", resultList.get(position).getSectionId());
						intent.putExtra("position", position);
						activity.startActivityForResult(intent, AppConfig.REQUEST_CLUB);
					}

				}
			});
			return view;
		}

		class ViewHolder {

			TextView club_title, description, member_number;
			LinearLayout keyword_layout;
			ImageView club_img;
			Button btn_focus;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
		if (requestCode == AppConfig.REQUEST_CLUB) {
			if (resultCode == RESULT_OK) {

				int position = data.getIntExtra("position", 0);
				Object object = dataAdapter.getItem(position);
				if (object instanceof ClubBean) {
					ClubBean mClubBean = (ClubBean) object;
					String screenFlag = resultList.get(position).getScreenFlag();
					if ("0".equals(screenFlag)) {
						screenFlag = "1";
					} else {
						screenFlag = "0";
					}
					mClubBean.setScreenFlag(screenFlag);
					dataAdapter.notifyDataSetChanged();
				}
			}
		} else if (requestCode == 0) {
			if (resultCode == RESULT_OK) {
				if (data.getStringExtra("name") != null) {
					keyword = data.getStringExtra("name");
					flgMore = false;
					pageNo = "0";
					getSeller(keyword);

				}
			}

		}

	}

	/**
	 * 关注
	 * 
	 * @param sectionId
	 */
	@SuppressWarnings("unchecked")
	private void followJsonData(String sectionId) {

		List<NameValuePair> params = new ArrayList<NameValuePair>(); // 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "specialFocusNew1")); // 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		params.add(new BasicNameValuePair("sectionId", sectionId));

		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				stopProgressDialog();
				String result = (String) object;
				Gson gson = new Gson();
				try {
					mCloudBeansBean = gson.fromJson(result, CloudBeansBean.class);
				} catch (Exception e) {
					return;
				}
				if ("0".equals(mCloudBeansBean.getResultCode())) {

				} else {
					stopProgressDialog();
					Alert.info(ClubActivity.this, result);
				}
			}

			@Override
			public void onFail(String exception) {

				Alert.error(ClubActivity.this,"与服务器连接失败，请检查网络");

			}
		}, GroupBean.class, AppConfig.CLUB).execute(params);
	}

	@Override
	public void onRefresh() {
		flgMore = false;
		resultList.clear();
		pageNo = "0";
		getSeller(keyword);

	}

	@Override
	public void onLoadMore() {

		flgMore = true;
		pageNo = String.valueOf(Integer.parseInt(pageNo) + 1);
		getSeller(keyword);

	}

	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(this);
			progressDialog.setMessage("正在加载...");
		}

		progressDialog.show();
	}

	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

}